//
//  LoopComposeViewController.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/15.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import SVProgressHUD

let basicIndex = 100

enum ToolBarBtn: Int{
    case Picture = 100
    case AtSome
    case Topic
    case Emoticon
    case More
}

class LoopComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        setNav()
        setTextView()
        setComposeSelector()
        setToolBar()
        registNotification()
//        textView.inputView = keyBoardView
//        textView.becomeFirstResponder()
        
    }
    
    //底部工具栏加载
    lazy var toolBar:UIStackView = {
   
        let bottomBar = UIStackView(frame: CGRect.zero)
//        bottomBar.backgroundColor = UIColor.red
        bottomBar.axis = .horizontal
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
   
    //NAV右侧发送按钮
    lazy var rightBarButton:UIBarButtonItem = {
    
        let rightBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 35))
        rightBtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        rightBtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        rightBtn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        rightBtn.setTitle("Send", for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30)
//        rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30)
        rightBtn.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        rightBtn.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .disabled)
//        rightBtn.sizeToFit()
        rightBtn.addTarget(self, action: #selector(sendWeibo), for: .touchUpInside)
        let barBtn = UIBarButtonItem(customView: rightBtn)
        barBtn.isEnabled = false
        return barBtn
    }()
    
    //NAV左侧取消按钮
    lazy var leftBarButton:UIBarButtonItem = {
    
        let leftBtn = UIButton(title: "Cancle", fontSize: 14, textColor: #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1))
        leftBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 35)
        leftBtn.setTitleColor(#colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1), for: .highlighted)
        leftBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0)
        leftBtn.addTarget(self, action: #selector(clickCancleBtn), for: .touchUpInside)
        let barBtn = UIBarButtonItem(customView: leftBtn)
        return barBtn
        
    }()
    
    lazy var textView:UITextView = {
    
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.textColor = UIColor.black
        textView.keyboardDismissMode = .onDrag
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    lazy var placeHolderLabel:UILabel = {
    
        let lbl = UILabel(title: "What's on your mind", fontsize: 18, textColor: #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1))
        return lbl
    }()
   
    
    lazy var composePicVc:LoopComposePicViewController = {
    
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: picSelectorWidth, height: picSelectorWidth)
        flowLayout.minimumLineSpacing = 1
        flowLayout.minimumInteritemSpacing = 1
        flowLayout.sectionInset = UIEdgeInsetsMake(0, picSelectorMargin, 0, picSelectorMargin)

        let base:LoopComposePicViewController = LoopComposePicViewController(collectionViewLayout: flowLayout)
        base.view.backgroundColor = UIColor.white
        base.collectionView?.backgroundColor = UIColor.white
        return base
    
    }()
    
    lazy var locationView:LoopLocationView = {
    
        let loc = LoopLocationView()
        return loc
    }()
    
    lazy var keyBoardView:HMEmoticonKeyboardView = {
    
        let keyBoard = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: emoticonKeyboardHeight))
        
        return keyBoard
    }()
    
    //注册通知
    private func registNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(changeSendBtnState), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmotion(noti:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension LoopComposeViewController{
    
    func insertEmotion(noti:Notification){
        let emotion = noti.object as? HMEmoticon
        
        textView.inputEmoticon(emoticon: emotion)
    }
    
    func setComposeSelector(){
    
        addChildViewController(composePicVc)
        self.view.addSubview(composePicVc.view)
        
        composePicVc.view.snp.makeConstraints({ (make) in
            make.bottom.leading.trailing.equalTo(self.view)
            make.height.equalTo(screenHeight / 3 * 2)
        })
    }

    func setNav(){
    
        self.navigationItem.leftBarButtonItem = leftBarButton
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        let lblTitle = UILabel()
        lblTitle.textAlignment = .center
        lblTitle.font = UIFont.systemFont(ofSize: 16)
        lblTitle.numberOfLines = 0
        if let textName = LoopUserAccountViewModel.shared.userAccount?.name{
            let text = "New Weibo\n\(textName)"
            lblTitle.text = text
            let strMA = NSMutableAttributedString(string: text)
            let range = (text as NSString).range(of: textName)
            strMA.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.lightGray], range: range)
            lblTitle.attributedText = strMA
        }else{
        
            lblTitle.text = "New Weibo"
        }
        lblTitle.sizeToFit()
        self.navigationItem.titleView = lblTitle
    }
    
    func setTextView(){
    
        self.view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        textView.becomeFirstResponder()
        
        textView.snp.makeConstraints { (make) in
            make.leading.top.trailing.equalTo(self.view)
            make.height.equalTo(screenHeight / 3)
        }
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.leading.top.equalTo(textView).offset(8)
        }
    }
    
    func setToolBar(){
    
        self.view.addSubview(toolBar)
        self.view.addSubview(locationView)
        
        toolBar.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        locationView.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(toolBar.snp.top)
        }

        
        let imageArray = ["compose_toolbar_picture","compose_mentionbutton_background","compose_trendbutton_background","compose_emoticonbutton_background","compose_add_background"]
        for (index,imageName) in imageArray.enumerated() {
            let btn = UIButton()
            let imgNor = UIImage(named: imageName)
            let imgHighlight = UIImage(named: "\(imageName)_highlighted")
            btn.setImage( imgNor, for: .normal)
            btn.setImage(imgHighlight, for: .highlighted)
            btn.backgroundColor = UIColor(white: 0.9, alpha: 1)
            btn.tag = basicIndex + index
            btn.sizeToFit()
            btn.addTarget(self, action: #selector(clickToolBarBtn(btn:)), for: .touchUpInside)
            toolBar.addArrangedSubview(btn)
                    }
    }
    
    func clickToolBarBtn(btn:UIButton){
        
        let enumType = ToolBarBtn(rawValue: btn.tag)!
        
        switch enumType {
        case .Picture:
            print("Picture")
            composePicVc.userWillChoosePic(cell: nil)
        case .AtSome:
            print("AtSome")
        case .Topic:
            print("Topic")
        case .Emoticon:
            print("Emoticon")
//            textView.inputView = keyBoardView
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            self.textView.inputView = (self.textView.inputView == nil ? self.keyBoardView : nil)
            self.textView.reloadInputViews()

        case .More:
            print("More")

        }
    
    }

    func clickCancleBtn(){
        textView.endEditing(true)
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    }
    
    func sendWeibo(){
        let parameters = ["access_token" : LoopUserAccountViewModel.shared.access_token,
                          "status" : textView.text]
        if composePicVc.picSelectedArray.count == 0 {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            LoopNetWorkManager.shared.request(HTTPMethod: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
                if error != nil{
                    SVProgressHUD.showError(withStatus: errorTip)
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "Sent")
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    
//                    SVProgressHUD.dismiss()
                    self.clickCancleBtn()
                    
                })
            }
        }else{
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            LoopNetWorkManager.shared.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                
                for image in self.composePicVc.picSelectedArray{
                    let imageData = UIImagePNGRepresentation(image)
                    
                    formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "\(Date())", mimeType: "application/octet-stream")
                }
            }, progress: nil, success: { (_, _) in
                
                SVProgressHUD.show(withStatus: "Sent")
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    self.clickCancleBtn()
                })
            }, failure: { (_, _) in
                
                SVProgressHUD.show(withStatus: "faile")
            })
            
        }
        
        
        
    }
    
    func changeSendBtnState(){
        rightBarButton.isEnabled = textView.hasText
        placeHolderLabel.isHidden = textView.hasText
        locationView.lblCount.isHidden = !textView.hasText
        locationView.lblCount.text = "\(textView.text.characters.count)"
    }
    
    func keyBoardChangeFrame(n:Notification){
//        print(n)
        //弹出
        //AnyHashable("UIKeyboardFrameBeginUserInfoKey"): NSRect: {{0, 568}, {320, 253}}
        //AnyHashable("UIKeyboardFrameEndUserInfoKey"): NSRect: {{0, 315}, {320, 253}},
        //收回
        //AnyHashable("UIKeyboardFrameBeginUserInfoKey"): NSRect: {{0, 315}, {320, 253}}
        //AnyHashable("UIKeyboardFrameEndUserInfoKey"): NSRect: {{0, 568}, {320, 253}},
        
        let frame = n.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        let offSet = -(screenHeight - frame.origin.y)
        
        UIView.animate(withDuration: 0.25) {
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offSet)
            })
        }
    }
}
